import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface Todo {
  id: number
  text: string
  completed: boolean
  createdAt: Date
}

/**
 * Todo Store
 * 管理待办事项的状态和操作
 */
export const useTodoStore = defineStore('todo', () => {
  const todos = ref<Todo[]>([])
  const nextId = ref(1)

  /**
   * 计算已完成的待办事项数量
   */
  const completedCount = computed(() => 
    todos.value.filter(todo => todo.completed).length
  )

  /**
   * 计算未完成的待办事项数量
   */
  const pendingCount = computed(() => 
    todos.value.filter(todo => !todo.completed).length
  )

  /**
   * 添加新的待办事项
   */
  const addTodo = (text: string) => {
    const newTodo: Todo = {
      id: nextId.value++,
      text,
      completed: false,
      createdAt: new Date()
    }
    todos.value.push(newTodo)
  }

  /**
   * 切换待办事项的完成状态
   */
  const toggleTodo = (id: number) => {
    const todo = todos.value.find(t => t.id === id)
    if (todo) {
      todo.completed = !todo.completed
    }
  }

  /**
   * 删除待办事项
   */
  const removeTodo = (id: number) => {
    const index = todos.value.findIndex(t => t.id === id)
    if (index > -1) {
      todos.value.splice(index, 1)
    }
  }

  /**
   * 清空所有已完成的待办事项
   */
  const clearCompleted = () => {
    todos.value = todos.value.filter(todo => !todo.completed)
  }

  /**
   * 清空所有待办事项
   */
  const clearAll = () => {
    todos.value = []
    nextId.value = 1
  }

  return {
    todos,
    completedCount,
    pendingCount,
    addTodo,
    toggleTodo,
    removeTodo,
    clearCompleted,
    clearAll
  }
}) 